package vip.xiaonuo.sys.modular.wechat.api.controller;

import com.qq.weixin.mp.aes.AesException;
import com.qq.weixin.mp.aes.WXBizMsgCrypt;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import vip.xiaonuo.sys.modular.wechat.api.service.WechatService;

import java.io.IOException;

/**
 * @author zjt
 * @description 企业微信回调
 * @date 2025/7/14 18:35
 */
@RestController
@RequestMapping("/wechat")
@RequiredArgsConstructor
public class WechatController {

    private final WechatService wechatService;

    /**
     * 企业微信回调验证Url
     *
     * @return
     */
    @Operation(summary = "企业微信回调地址")
    @GetMapping("/callback")
    public void wechatCallBackP(@RequestParam("msg_signature") String msg_signature,
                                @RequestParam("nonce") String nonce,
                                @RequestParam("timestamp") String timestamp,
                                @RequestParam(value = "echostr", required = false) String echostr,
                                HttpServletResponse response) throws IOException {
        try {
            // 2. 初始化加密工具
            String token = "84n2S8x2so9rLmeouD";
            String aesKey = "QzhAXVomBdrDjaY1e5xduCl8dkhOr6WMaief2tmF4ze";
            String corpId = "wwe4c18b63c565e438";
            WXBizMsgCrypt wxBizMsgCrypt = new WXBizMsgCrypt(token, aesKey, corpId);

            String verifyMsg = wxBizMsgCrypt.verifyUrl(msg_signature, timestamp,
                    nonce, echostr);
            response.setContentType("text/plain;charset=UTF-8");
            response.getWriter().print(verifyMsg);
        } catch (Exception e) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "处理失败");
        }
    }

    /**
     * 企业微信回调地址
     *
     * @return
     */
    @Operation(summary = "企业微信回调地址")
    @PostMapping("/callback")
    public void wechatCallBack(@RequestParam("msg_signature") String msgSignature, @RequestParam("timestamp") String timestamp, @RequestParam("nonce") String nonce, @RequestBody String postData) throws AesException {
        wechatService.callback(msgSignature, timestamp, nonce, postData);
    }

    /**
     * 手动调用企业微信回调
     *
     * @return
     */
    @Operation(summary = "企业微信回调地址")
    @PutMapping("/callback")
    public void wechatEvent(@RequestBody String wechatEventMessage) {
        wechatService.wechatEvent(wechatEventMessage);
    }
}
